
import React, { Component } from 'react';
import {
	StyleSheet, Text, FlatList, Animated, View, Image, TouchableOpacity, Alert
} from "react-native";
import { NavigationEvents } from 'react-navigation';
import moment from 'moment';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import ToastUtil from '../../../utils/toast';
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import Dictionary from '../../../utils/dictionary';
import { Common } from '../../../component/common/Common.js';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
import { NewAccountHome } from '../../../components/common/newAccountHome';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { ApplyOfferCard } from '../_components/ApplyOfferCard';
import { OfferCommon } from '../_common/common';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { ApplyListCard } from '../_components/ApplyListCard';
import { ProgressModal } from '../../../components/common/ProgressModal';
import { CommonDialog } from '../../../components/common/Dialog';

const scale = GLOBAL.SCALE;
const selectIcon = require('../../../imgs/select.png')
const correct = require('../../../imgs/global/correct.png');

export class TransApprovalDetail extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '报盘成交申请审批',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	constructor(props) {
		super(props);
		let { item } = this.props.navigation.state.params
		let applyIdList = []
		item.packageResourceList.map(item => {
			applyIdList.push(item.applyId)
		})
		this.state = {
			status: 'data',
			resData: [],
			refreshIcon: false,
			modalVisible: false,
			lightBoxData: {
				modalVisible: false,
				onClosePress: this._closeLightBox,
				title: '审批流',
				rowDataList: [],
				status: 'data',
				refreshIcon: false,
			},
		}
		this.pageParams = {
			bizModel: item.bizModel,
			winRule: item.bizModel === 'Z' ? item.winRule : 'SINGLE',
			applyIdList
		}
		this.businessKeyList = []
		this.selectData = {};
	}

	async componentWillMount() {
		// await this.getSorage();
		await this.initPage();
	}

	async initPage() {
		this.setState({
			status: 'loading',
			refreshIcon: true,
		})
		let resData = await HTTP.POST(API_GENERATE(API.BIZ_APPLY_LIST), this.pageParams)
		if (resData) {
			this.setState({
				resData,
				status: resData ? 'data' : 'empty',
				refreshIcon: false,
				isAll: false
			})
		}
		else {
			this.setState({
				state: 'error'
			})
		}
	}

	// 同意
	auditPress = (type, item) => {
		let { resData } = this.state
		this.auditResult = type;
		this.remark = '';
		this.selectData = item;
		this.businessKeyList = []
		let { salesType } = this.props.navigation.state.params;
		if (item) {
			this.props.navigation.navigate('PackOfferSituation', {
				bidPackageId: item.bidPackageId,
				winRule: this.pageParams.winRule,
				salesType: salesType,
				applyId: item.applyId,
				type: this.pageParams.bizModel == 'M' ? 'MULTIPLE' : 'APPROVE',
				periodNum: item.periodNum
			})
		} else {
			resData.map(i => {
				if (i.selectList) {
					this.businessKeyList.push(i.applyId)
				}
			})
			if (this.businessKeyList.length == 0) {
				ToastUtil.showWarning('请先选择审批对象')
			}
			else {
				console.log(this.businessKeyList)
				this.setState({
					showRejectModal: true,
				})
			}

		}
	}

	// 审批
	approve = async () => {
		let requestParams = {
			remark: this.remark,
			auditResult: this.auditResult,
			businessKeyList: this.businessKeyList
		};
		let text = this.auditResult ? '审批' : '驳回';
		this.setState({
			showRejectModal: false,
			status: 'loading'
		})
		let res = await HTTP.POST(API_GENERATE(API.DEAL_AUDIT_BATCH), requestParams);
		if (res) {
			ToastUtil.showSuccess(`${text}成功`).then(() => {
				this.props.navigation.navigate('TransApprovalList')
			})
		} else {
			this.setState({
				status: 'error'
			})
		}
	}

	// 查看审批流
	_getCheckApprove = async (data) => {
		let { corpId } = this.props.navigation.state.params
		let { applyId, processInstanceId } = data.item || {};
		//查询审批节点AUDIT_QUERY_COMPANY
		let params = {
			bizId: applyId,
			bizObjType: 'BID_BARGAIN',
			processInstanceId,
			corpId,
		}
		let responseData = await HTTP.GET(API_GENERATE(API.APPROVAL_NODE), params);
		console.log('responseData', responseData)
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = true;
		lightBoxData.title = '审批流';
		lightBoxData.rowDataList = responseData;
		this.setState({
			lightBoxData,
			status: 'data'
		})
	}
	_closeLightBox = () => {
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = false;
		this.setState({ lightBoxData });
	}
	dateFormat(date) {
		return date ? `${moment(date).format('YYYY-MM-DD')} ${date.substring(11, 16)}` : '-'
	}
	onErrorRefresh = () => {
		this.initPage();
	}
	_selectAll = () => {
		let { resData, isAll } = this.state;
		isAll = !isAll;
		resData.map((item) => {
			item.selectList = isAll
		})
		this.setState({
			resData,
			isAll
		});
	}
	changeCheck = (index) => {
		let { resData, isAll } = this.state;
		resData[index].selectList = !resData[index].selectList
		let num = 0
		resData.map((item, i) => {
			if (item.selectList) {
				num++
			}
		})
		if (num === resData.length) {
			isAll = true
		}
		else {
			isAll = false
		}
		this.setState({
			resData, isAll
		});
	}
	_approvalListItim = (data) => {
		let { salesType } = this.props.navigation.state.params;
		let { bidPackageName, upTime, packageResourceList, lastUpdateTime, bidPackageId, applyTypeName, statusName, createByName, teamName, comments, selectList } = data.item;
		return (
			<View style={{ paddingLeft: 12 * scale, paddingRight: 12 * scale, marginTop: 12 * scale, marginBottom: 12 * scale }}>
				<View style={styles.itemTimeData}>
					<Text style={styles.itemLightText}>{bidPackageId || '-'}</Text>
					<Text style={styles.itemLightText}>申请时间：{this.dateFormat(lastUpdateTime)}</Text>
				</View>
				<View style={styles.itemWrap}>
					<View style={styles.itemName}>
						<TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }} onPress={() => this.changeCheck(data.index)}>
							<View>
								<View style={styles.lockView}>
									{
										selectList ? <Image style={styles.lockImage} source={correct} /> : null
									}
								</View>
							</View>
							<Text style={styles.itemBoldTitle}>{bidPackageName || ''}</Text>
						</TouchableOpacity>
						<Text style={styles.offerTitleRed}>{applyTypeName && statusName ? (applyTypeName + statusName) : null}</Text>
					</View>
					<View style={{ flexDirection: 'row', alignItems: 'flex-start', paddingLeft: 12 * scale }}>
						<Text style={{ fontSize: 12 * scale, paddingBottom: 12 * scale }}>上架：{this.dateFormat(upTime) || '-'} </Text>
					</View>
					<View style={{ flexDirection: 'row', justifyContent: 'space-between', flexWrap: 'wrap', paddingLeft: 12 * scale, marginBottom: 10 * scale }}>
						<Text style={{ fontSize: 12 * scale, color: '#000', marginBottom: 10 * scale }}>申请人：{createByName}{teamName ? '（' + teamName + '）' : null}</Text>
						<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: "center", marginRight: 15 * scale, marginBottom: 10 * scale }}>
							<TouchableOpacity style={[styles.cardWhyBox, { paddingLeft: 0 }]} onPress={() => { this._getCheckApprove(data) }}>
								<Text style={styles.textThemeColor}>审批流</Text>
							</TouchableOpacity>
							{comments ?
								<Text style={styles.textThemeColor}> | </Text> : null}
							{comments ?
								<TouchableOpacity style={styles.cardWhyBox} onPress={() => { this.setState({ modalVisible: true, message: comments }) }}>
									<Text style={styles.textThemeColor}>申请原因</Text>
								</TouchableOpacity>
								: null
							}
						</View>
					</View>
					<View style={styles.itemBorder}></View>
					<View style={styles.itemBody}>
						{packageResourceList && packageResourceList.map((item, index) => {
							return (
								<View style={styles.offerItem} key={index}>
									{item.goodsName ?
										<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 * scale }}>
											<Text style={styles.offerTitle}>{item.goodsName}</Text>
										</View>
										: null
									}
									<ApplyListCard item={item} winRule={this.pageParams.winRule} bizModel={this.pageParams.bizModel} salesType={salesType} key={index} />
								</View>
							)
						})
						}
					</View>
					<View>
						<View style={styles.itemDayTime}>
							<TouchableOpacity style={styles.consent} onPress={() => { this.auditPress(1, data.item) }}>
								<Text style={styles.consentText}>同意</Text>
							</TouchableOpacity>
							<TouchableOpacity style={styles.itemdown} onPress={() => { this.auditPress(0, data.item) }}>
								<Text style={styles.itemdownText}>驳回</Text>
							</TouchableOpacity>
						</View>
					</View>
				</View>
			</View>
		)
	}
	render() {
		let { resData, showRejectModal, status, refreshIcon, lightBoxData, modalVisible, message, isAll } = this.state;
		return (
			<View style={styles.container}>
				{
					status == 'data' ? (
						(
							<View style={styles.body}>
								<FlatList
									data={resData}
									renderItem={this._approvalListItim}
									refreshing={refreshIcon}
									onRefresh={() => { this.initPage() }}
								/>
								<View style={styles.bottomContainer}>
									<TouchableOpacity onPress={this._selectAll} style={styles.selectBox}>
										<View style={styles.lockView}>
											{
												isAll ? <Image style={styles.lockImage} source={correct} /> : null
											}
										</View>
										<Text style={styles.selectAll}>全选</Text>
									</TouchableOpacity>
									<View style={styles.btnBox}>
										<TouchableOpacity style={styles.consent} onPress={() => { this.auditPress(1) }}>
											<Text style={styles.consentText}>同意</Text>
										</TouchableOpacity>
										<TouchableOpacity style={styles.itemdown} onPress={() => { this.auditPress(0) }}>
											<Text style={styles.itemdownText}>驳回</Text>
										</TouchableOpacity>
									</View>
								</View>
							</View>

						)
					) : (<View style={{ flex: 1 }}>
						<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />
					</View>)
				}
				<RefuseModal
					titleText={'审批意见'}
					placeholderText={this.auditResult ? '请输入同意原因' : null}
					propsDefaultValue={this.auditResult ? '审批同意' : ''}
					visible={showRejectModal}
					btnPress={(text) => {
						this.remark = text;
						this.approve();
					}}
					bgPress={() => {
						this.setState({
							showRejectModal: false,
						});
					}} />
				<ProgressModal {...lightBoxData} />
				<CommonDialog modalVisible={modalVisible} title={'申请原因'} text={message} onClosePress={() => { this.setState({ modalVisible: false }) }} />

			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	body: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	bottomContainer: {
		height: 60 * scale,
		width: '100%',
		backgroundColor: "#fff",
		flexDirection: 'row',
		justifyContent: 'space-between'
	},
	selectBox: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingLeft: 20 * scale,
	},
	btnBox: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
	},
	btnText: {
		fontSize: 13 * scale,
		textAlign: 'center',
		color: '#fff'
	},
	lockImage: {
		tintColor: style.color.themeColor,
		width: 8 * scale,
		height: 8 * scale
	},
	lockView: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		height: 12 * scale,
		width: 12 * scale,
		borderWidth: 1 * scale,
		borderColor: style.color.themeColor,
		marginRight: 5 * scale,
	},
	selectAllBox: {
		paddingLeft: 0 * scale
	},
	selectAll: {
		fontSize: 11 * scale,
	},
	btnClick: {
		backgroundColor: '#FA6400',
		height: 30 * scale,
		width: 78 * scale,
		borderRadius: 15 * scale,
		marginLeft: 10 * scale,
		borderWidth: 1 * scale,
		borderColor: '#FA6400',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
	},
	btnClickActive: {
		backgroundColor: "#fff",
		borderWidth: 1 * scale,
		borderColor: style.color.themeColor,
	},
	btnActive: {
		color: style.color.themeColor
	},
	itemBorder: {
		height: 1 * scale,
		backgroundColor: '#E3E7F0',
		marginBottom: 15 * scale,
	},
	consent: {
		paddingRight: 20 * scale,
		paddingLeft: 20 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderRadius: 15 * scale,
		backgroundColor: style.color.themeColor,
		overflow: 'hidden'
	},
	consentText: {
		fontSize: 12 * scale,
		color: '#ffffff',
	},
	itemdown: {
		paddingRight: 20 * scale,
		paddingLeft: 20 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderRadius: 15 * scale,
		marginRight: 20 * scale,
		marginLeft: 10 * scale,
	},
	itemdownText: {
		fontSize: 12 * scale,
		color: style.color.themeColor,
	},
	itemDayTime: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
		paddingLeft: 12 * scale,
		borderTopWidth: 1 * scale,
		borderTopColor: '#E3E7F0',
		height: 50 * scale,
	},
	itemCommonText: {
		fontSize: 12 * scale,
		marginBottom: 4 * scale
	},
	tabItem: {
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		paddingLeft: 16 * scale,
		paddingRight: 16 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		marginHorizontal: 10,
		borderWidth: 1,
		borderRadius: 20,
		borderColor: style.color.themeColor
	},
	tabText: {
		color: '#fff'
	},
	tabWrap: {
		backgroundColor: style.color.bgGray,
		flexDirection: 'row',
		alignItems: 'center',
		paddingTop: 15 * scale,
		paddingBottom: 10 * scale
	},
	itemLightText: {
		fontSize: 12 * scale,
		color: '#272727',
		fontWeight: '500',
	},
	itemTimeData: {
		marginBottom: 7 * scale,
		flexDirection: 'row',
		justifyContent: 'space-between',
	},
	itemWrap: {
		backgroundColor: '#fff',
		width: '100%',
		borderRadius: 8 * scale,
		marginTop: 6 * scale,
		paddingTop: 14 * scale,
	},
	itemName: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		marginBottom: 10 * scale,
		marginTop: 5 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,

	},
	itemBoldTitle: {
		fontSize: 12 * scale,
		color: '#272727',
		fontWeight: '900',
		width: 200 * scale
	},
	itemTitleStatus: {
		fontSize: 10 * scale,
		color: style.color.themeColor,
		paddingRight: 7 * scale,
		paddingLeft: 7 * scale,
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderRadius: 11 * scale
	},
	itemBorder: {
		height: 1 * scale,
		backgroundColor: '#E3E7F0',
		marginBottom: 15 * scale,
	},
	itemBody: {
		position: 'relative',
		overflow: 'hidden',
		backgroundColor: '#fff'
	},
	offerItem: {
		backgroundColor: '#fff',
		paddingBottom: 10 * scale,
		paddingHorizontal: 20 * scale,
		borderRadius: 6 * scale,
		marginBottom: 14 * scale
	},
	offerTitle: {
		fontSize: 13,
		color: '#000000',
		fontWeight: "600"
	},
	offerTitleRed: {
		fontSize: 12,
		color: '#CA0202',
		fontWeight: '600',
	},
	offerPackContent: {
		marginTop: 7 * scale,
		paddingVertical: 5 * scale,
	},
	cardWhyBox: {
	},
	textThemeColor: {
		fontSize: 12,
		color: style.color.themeColor
	},
})